package com.youdianstar.app.ui

import android.graphics.Typeface
import android.view.View
import androidx.activity.OnBackPressedCallback

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityOrderDetailsBinding
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.entity.OrderInfo
import com.youdianstar.app.entity.OrderDetailInfo
import com.youdianstar.app.entity.BillingPlan
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiStateObserver
import com.youdianstar.app.common.util.*
import com.youdianstar.app.support.paymentActionIntent
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.DataHelperEx
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Locale


/**
 * File: OrderDetailActivity
 * Author: 82149 Create: 2021/11/12 11:40
 * Changes (from 2021/11/12)
 * --------------------------------------------------
 * description: 订单详情
 * ---------------------------------------------------
 *
 */
class OrderDetailActivity : BaseActivity<ActivityOrderDetailsBinding, OrderViewModel>() {
    override fun layoutId(): Int = R.layout.activity_order_details

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): OrderViewModel {
        val model: OrderViewModel by viewModel()
        return model
    }

    //操作事件: 0-列表/主页查看详情 ,1-租借结果查看(要返回主页)
    private var actionType = 0
    private var orderNo: String? = null

    override fun initData() {
        super.initData()
        mBinding.headBar.initTitle(this, getString(R.string.order_orderDetail), showInner = false, isBackFinish = false,
            backAction = {
                backActionCallback()
            })
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true){
            override fun handleOnBackPressed() {
                backActionCallback()
            }
        })
        orderNo = intent.getStringExtra(Extra.IT_ORDERNO)
        orderNo?.let {
            showLoadingDialog("")
            // 首次加载时调用接口
            mViewModel.getOrderDetail(it)
        }
        actionType = intent.getIntExtra(Extra.IT_TYPE,0)
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        
        mViewModel.detailNetLiveData.observe(this, object : BaseApiStateObserver<OrderInfo>(mBinding.rotContainer) {
                override fun onReload(v: View?) {

                }

                override fun onDataResult(data: OrderInfo?) {
                    super.onDataResult(data)
                    dismissDialog()
                    data?.let {
                        // 优先使用新接口的OrderDetailInfo数据，如果没有则使用OrderInfo
                        mViewModel.currentOrderDetailInfo?.let { detailInfo ->
                            // 使用新接口数据，覆盖所有字段
                            setNewOrderLayout(detailInfo)
                            // 同时更新OrderInfo用于兼容旧逻辑
                            mViewModel.orderDetailsFiled.set(it)
                        } ?: run {
                            // 如果没有新接口数据，使用旧逻辑
                            mViewModel.orderDetailsFiled.set(it)
                            setOrderLayout(it)
                        }
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    dismissDialog()
                }
            })
    }

    override fun initClickEvent() {
        mBinding.btnPay.setThrottleListener {
            mViewModel.orderDetailsFiled.get()?.let { de: OrderInfo ->
                //跳转支付 待支付
                if (de.lost){
                    paymentActionIntent(this@OrderDetailActivity, BisType.Bis_Loss, de.money, orderNo = de.orderNo, orderInfo = de)
                }else{
                    paymentActionIntent(this@OrderDetailActivity, BisType.Bis_Rent, de.money, orderNo = de.orderNo, orderInfo = de)
                }
            }
        }
    }

    /**
     * 填充页面布局（旧接口数据适配新布局）
     * @param order 订单信息
     */
    private fun setOrderLayout(order: OrderInfo) {
        val symbolStr = DataAppManager.instance.symbolTx()
        
        // ========== 订单状态栏 ==========
        // 根据order.state设置状态图标和文本
        val statusDrawable = when (order.state) {
            DataCode.STATE_RENTING -> R.drawable.oval_order_renting       // 租借中 - 蓝色
            DataCode.STATE_COMPLETE, DataCode.STATE_CANCEL, DataCode.STATE_REFUND, DataCode.STATE_PURCHASE_PB -> R.drawable.oval_order_complete  // 已完成/已取消/已退款/购买充电宝 - 绿色
            DataCode.STATE_UNPAID -> R.drawable.oval_order_process         // 待支付 - 黄色
            DataCode.STATE_PROCESS -> R.drawable.oval_order_process        // 调查中 - 黄色
            DataCode.STATE_REPORT_LOSS -> R.drawable.oval_order_loss       // 已报失 - 红色
            else -> R.drawable.oval_order_process                          // 默认 - 黄色
        }
        mBinding.ivOrderStatus.setBackgroundResource(statusDrawable)
        
        // 根据状态生成文本
        val statusText = when (order.state) {
            DataCode.STATE_RENTING -> getString(R.string.order_renting)
            DataCode.STATE_COMPLETE, DataCode.STATE_CANCEL, DataCode.STATE_REFUND -> getString(R.string.order_completed)
            DataCode.STATE_UNPAID -> getString(R.string.order_pendingPayment)
            DataCode.STATE_PROCESS -> getString(R.string.order_underInvestigation)
            DataCode.STATE_REPORT_LOSS -> getString(R.string.order_completed)  // 已报失显示已完成
            DataCode.STATE_PURCHASE_PB -> getString(R.string.order_completed)
            else -> "--"
        }
        mBinding.tvOrderStatus.text = statusText
        
        // ========== 订单详情部分 ==========
        // 1. 订单编号
        mBinding.tvOrderNumber.text = order.orderNo
        
        // 2. 租借时间
        mBinding.tvRentalTime.text = DateUtil.getOrderTime(order.createTime)
        
        // 3. 租借地点
        mBinding.tvRentalLocation.text = order.getRentAddress()
        
        // 4. 归还时间
        if (order.endTime > 0 && order.state != DataCode.STATE_RENTING && order.state != DataCode.STATE_PROCESS && !order.lost) {
            mBinding.tvReturnTime.text = DateUtil.getOrderTime(order.endTime)
        } else {
            mBinding.tvReturnTime.text = "--"
        }
        
        // 5. 归还地点
        val returnAddress = if (order.lost) "--" else order.getReturnAddress()
        mBinding.tvReturnLocation.text = returnAddress
        
        // ========== 资费详情部分 ==========
        // 6. 产生费用
        val generatedFee = if (order.state == DataCode.STATE_COMPLETE || order.state == DataCode.STATE_CANCEL || order.state == DataCode.STATE_REFUND) {
            order.realAmountValue()
        } else {
            order.orderAmountValue()
        }
        mBinding.tvGeneratedFee.text = "$symbolStr ${MathUtil.round(generatedFee)}"
        mBinding.tvGeneratedFee.setTextColor(getViewColor(this, R.color.color_FF6400))
        
        // 7. 使用时长
        val useTime: Long = if (order.state == DataCode.STATE_RENTING) {
            System.currentTimeMillis() - order.createTime
        } else {
            order.getOrderDuration() * 1000
        }
        val timeArray = DateUtil.time2ArrayTime(useTime)
        val dayStr = DateUtil.time0format(timeArray[0])
        val hrStr = DateUtil.time0format(timeArray[1])
        val minStr = DateUtil.time0format(timeArray[2])
        val secStr = DateUtil.time0format(timeArray[3])
        val durationText = if (timeArray[0] > 0) {
            if (timeArray[0] > 1) {
                String.format(getString(R.string.Order_duration_days), secStr, minStr, hrStr, dayStr)
            } else {
                String.format(getString(R.string.Order_duration_day), secStr, minStr, hrStr, dayStr)
            }
        } else {
            String.format(getString(R.string.Order_duration_text), secStr, minStr, hrStr)
        }
        mBinding.tvUsageDuration.text = durationText
        
        // 8. 计费规则
        order.billing?.let { plan ->
            mBinding.tvBillingRule.text = DataHelperEx.pricePlanTx(this, plan)
        } ?: run {
            mBinding.tvBillingRule.text = "--"
        }
        
        // 9. 支付状态
        val paymentStatusText = when (order.state) {
            DataCode.STATE_RENTING -> getString(R.string.order_renting)
            DataCode.STATE_COMPLETE, DataCode.STATE_CANCEL, DataCode.STATE_REFUND -> getString(R.string.order_completed)
            DataCode.STATE_UNPAID -> getString(R.string.order_pendingPayment)
            DataCode.STATE_PROCESS -> getString(R.string.order_underInvestigation)
            DataCode.STATE_REPORT_LOSS -> getString(R.string.order_completed)
            else -> "--"
        }
        mBinding.tvPaymentStatus.text = paymentStatusText
        
        // 10. 押金方式 - 隐藏（旧接口可能没有此字段）
        mBinding.llDepositMethodContainer.visibility = View.GONE
        
        // 11. 押金金额 - 隐藏（旧接口可能没有此字段）
        mBinding.llDepositAmountContainer.visibility = View.GONE
        
        // ========== 租借设备信息部分 ==========
        // 12. 租借柜机SN
        mBinding.tvRentalCabinetSn.text = if (StrUtil.isEmpty(order.rentCabinetNo)) "--" else order.rentCabinetNo
        
        // 13. 充电宝SN
        mBinding.tvPowerbankSn.text = order.pbNo ?: "--"
        
        // ========== 归还设备信息部分 ==========
        // 14. 归还柜机SN
        val hasReturnInfo = !StrUtil.isEmpty(order.returnCabinetNo) && 
                           order.state != DataCode.STATE_RENTING && 
                           order.state != DataCode.STATE_PROCESS && 
                           order.reportState != 1 &&
                           !order.lost
        
        if (hasReturnInfo) {
            mBinding.tvSectionReturnDevice.visibility = View.VISIBLE
            mBinding.llReturnDevice.visibility = View.VISIBLE
            mBinding.tvReturnCabinetSn.text = order.returnCabinetNo
        } else {
            mBinding.tvSectionReturnDevice.visibility = View.GONE
            mBinding.llReturnDevice.visibility = View.GONE
        }
        
        // ========== 支付按钮 ==========
        // 15. 控制支付按钮显示
        mBinding.llBottom.visibility = if (order.state == DataCode.STATE_UNPAID) View.VISIBLE else View.GONE
    }
    
    /**
     * 使用新接口字段完整显示订单详情（覆盖所有字段）
     * @param detailInfo 新接口返回的订单详情数据
     */
    private fun setNewOrderLayout(detailInfo: OrderDetailInfo) {
        val symbolStr = DataAppManager.instance.symbolTx()
        
        // ========== 订单状态栏 ==========
        // 根据usingStatus设置状态图标和文本
        val statusDrawable = when (detailInfo.usingStatus) {
            1 -> R.drawable.oval_order_renting      // 使用中 - 蓝色
            2 -> R.drawable.oval_order_complete    // 已归还 - 绿色
            3 -> R.drawable.oval_order_complete    // 已购买(超时) - 绿色
            4 -> R.drawable.oval_order_loss        // 已购买(丢失) - 红色
            5 -> R.drawable.oval_order_complete    // 已购买(其他) - 绿色
            else -> R.drawable.oval_order_process   // 其他状态 - 黄色
        }
        mBinding.ivOrderStatus.setBackgroundResource(statusDrawable)
        
        // 根据usingStatus获取国际化文本
        val statusTextRes = when (detailInfo.usingStatus) {
            1 -> R.string.order_status_using           // 使用中
            2 -> R.string.order_status_returned         // 已归还
            3 -> R.string.order_status_purchased_timeout  // 已购买(超时)
            4 -> R.string.order_status_purchased_lost     // 已购买(丢失)
            5 -> R.string.order_status_purchased          // 已购买(其他)
            else -> R.string.order_status_unknown         // 未知状态
        }
        mBinding.tvOrderStatus.setText(statusTextRes)
        
        // ========== 订单详情部分 ==========
        // 1. 订单编号
        mBinding.tvOrderNumber.text = detailInfo.uuid
        
        // 2. 租借时间
        mBinding.tvRentalTime.text = DateUtil.getProjectTime(
            detailInfo.createTime,
            DateUtil.DATEFORMATYMDHMS
        )
        
        // 3. 租借地点
        mBinding.tvRentalLocation.text = if (StrUtil.isEmpty(detailInfo.box1SiteName)) "--" else detailInfo.box1SiteName
        
        // 4. 归还时间
        val returnTime = detailInfo.returnTime
        if (returnTime != null && returnTime > 0) {
            mBinding.tvReturnTime.text = DateUtil.getProjectTime(
                returnTime,
                DateUtil.DATEFORMATYMDHMS
            )
        } else {
            mBinding.tvReturnTime.text = "--"
        }
        
        // 5. 归还地点
        mBinding.tvReturnLocation.text = if (StrUtil.isEmpty(detailInfo.box2SiteName)) "--" else detailInfo.box2SiteName
        
        // ========== 资费详情部分 ==========
        // 6. 产生费用 - 使用fee，显示橙色
        val feeAmount = detailInfo.fee
        mBinding.tvGeneratedFee.text = "$symbolStr ${MathUtil.round(feeAmount)}"
        mBinding.tvGeneratedFee.setTextColor(getViewColor(this, R.color.color_FF6400))
        
        // 7. 使用时长 - 优先使用distanceTime
        mBinding.tvUsageDuration.text = detailInfo.distanceTime ?: "--"
        
        // 8. 计费规则 - 使用DataHelperEx.pricePlanTx格式化
        val billingPlan = BillingPlan(
            freeDuration = detailInfo.ruleMinuteFree,
            freeDurationControlType = 1,
            freeLimit = 0,
            cycle = detailInfo.ruleMinuteCycle,
            amount = detailInfo.ruleCycleFee.toFloat(),
            dayAmount = detailInfo.ruleDayFee.toFloat(),
            penaltyAmount = 0f,
            controlType = 1,
            maxRentDuration = 0,
            maxDurationControlType = 1,
            isSystem = false
        )
        mBinding.tvBillingRule.text = DataHelperEx.pricePlanTx(this, billingPlan)
        
        // 9. 支付状态
        val paymentStatusText = when {
            detailInfo.usingStatus == 1 -> getString(R.string.order_renting)
            detailInfo.usingStatus == 2 && detailInfo.pay -> getString(R.string.order_completed)
            detailInfo.usingStatus == 2 && !detailInfo.pay -> getString(R.string.order_pendingPayment)
            detailInfo.usingStatus in listOf(3, 4, 5) -> getString(R.string.order_completed)
            else -> "--"
        }
        mBinding.tvPaymentStatus.text = paymentStatusText
        
        // 10. 押金方式
        if (detailInfo.security && !StrUtil.isEmpty(detailInfo.payWay)) {
            mBinding.llDepositMethodContainer.visibility = View.VISIBLE
            val payWayText = when (detailInfo.payWay?.toLowerCase(Locale.getDefault())) {
                "momo" -> "MoMo"
                "zalopay" -> "ZaloPay"
                "vnpay" -> "VNPAY"
                "security" -> getString(R.string.pay_deposit)
                "bankcard", "creditcard" -> getString(R.string.wallet_type_bankcard)
                "applepay" -> getString(R.string.wallet_type_applepay)
                "googlepay" -> getString(R.string.wallet_type_googlepay)
                else -> detailInfo.payWay ?: "--"
            }
            mBinding.tvDepositMethod.text = payWayText
        } else {
            mBinding.llDepositMethodContainer.visibility = View.GONE
        }
        
        // 11. 押金金额
        if (detailInfo.security && detailInfo.securityFee > 0) {
            mBinding.llDepositAmountContainer.visibility = View.VISIBLE
            mBinding.tvDepositAmount.text = "$symbolStr ${MathUtil.round(detailInfo.securityFee)}"
        } else {
            mBinding.llDepositAmountContainer.visibility = View.GONE
        }
        
        // ========== 租借设备信息部分 ==========
        // 12. 租借柜机SN
        mBinding.tvRentalCabinetSn.text = if (StrUtil.isEmpty(detailInfo.box1DeviceId)) "--" else detailInfo.box1DeviceId
        
        // 13. 充电宝SN
        mBinding.tvPowerbankSn.text = if (StrUtil.isEmpty(detailInfo.singleDeviceUuid)) "--" else detailInfo.singleDeviceUuid
        
        // ========== 归还设备信息部分 ==========
        // 14. 归还柜机SN（如果有归还信息则显示）
        val hasReturnInfo = returnTime != null && returnTime > 0 && !StrUtil.isEmpty(detailInfo.box2DeviceId)
        if (hasReturnInfo) {
            mBinding.tvSectionReturnDevice.visibility = View.VISIBLE
            mBinding.llReturnDevice.visibility = View.VISIBLE
            mBinding.tvReturnCabinetSn.text = if (StrUtil.isEmpty(detailInfo.box2DeviceId)) "--" else detailInfo.box2DeviceId
        } else {
            mBinding.tvSectionReturnDevice.visibility = View.GONE
            mBinding.llReturnDevice.visibility = View.GONE
        }
        
        // ========== 支付按钮 ==========
        // 15. 控制支付按钮显示
        if (detailInfo.usingStatus == 2 && !detailInfo.pay) {
            // 已归还但未支付 - 显示支付按钮
            mBinding.llBottom.visibility = View.VISIBLE
        } else {
            // 其他状态 - 隐藏支付按钮
            mBinding.llBottom.visibility = View.GONE
        }
    }

    private fun backActionCallback(){
        if (actionType == 1){
            startActivity<MainActivity>()
        }
        finish()
    }

    override fun onResume() {
        super.onResume()
        
        // 每次进入页面时调用一次订单详情接口
        orderNo?.let {
            mViewModel.getOrderDetail(it)
        }
    }

    override fun onDestroy() {
        mViewModel.cancelDetailCount()
        super.onDestroy()
    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            backActionCallback()
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }


}